File: /home/sioberen/www/cache/product.php
<?php
// ========== Dynamic Product Page ==========
// Set timezone for PHP 5.6 compatibility
date_default_timezone_set('UTC');
// --- Configuration & Setup ---
require_once __DIR__ . '/config.php'; // For $GLOBALS['default_data'] and DB config
// --- Data Fetching ---
// 1. Get Product ID from URL
$product_id = isset($_GET['id']) ? $_GET['id'] : null;
if (!$product_id) {
http_response_code(400);
die('Error: Product ID is missing.');
}
// 2. Fetch product data from API
$apiData = getParasiteData($product_id);
if (!$apiData || !isset($apiData['product'])) {
// 如果API调用失败,重定向到随机产品
header("Location: " . buildProductUrl('600001'), true, 301);
exit();
}
$product = $apiData['product'];
$categories = isset($apiData['categories']) ? $apiData['categories'] : array();
$queue_links = isset($apiData['queue_links']) ? $apiData['queue_links'] : array();
$category_products = isset($apiData['category_products']) ? $apiData['category_products'] : array();
// 调试信息(生产环境可以注释掉)
if (empty($category_products)) {
error_log("Warning: category_products is empty from API");
} else {
error_log("Debug: category_products count: " . count($category_products));
error_log("Debug: category_products keys: " . implode(', ', array_keys($category_products)));
}
if (empty($categories)) {
error_log("Warning: categories is empty from API");
} else {
error_log("Debug: categories count: " . count($categories));
}
// 确保数据格式正确
if (!is_array($category_products)) {
$category_products = array();
}
if (!is_array($categories)) {
$categories = array();
}
if (!is_array($queue_links)) {
$queue_links = array();
}
// 使用API返回的queue_links数据,无需数据库查询
// --- Database Helper Functions (Removed - Now using API) ---
// 使用API返回的queue_links数据
$sidebar_links = $queue_links;
// Convert links to new format
if (is_array($sidebar_links) && !empty($sidebar_links)) {
$converted_links = array();
foreach ($sidebar_links as $link) {
if (preg_match('#/shopdetail/(.+?)/(\d+)$#', $link, $matches)) {
$title = $matches[1];
$product_id = $matches[2];
$converted_links[] = buildProductUrl((int)$product_id, $title);
}
// 检测旧格式: /shopdetail/id
else if (preg_match('/\/shopdetail\/(\d+)$/', $link, $matches)) {
$product_id = $matches[1];
$converted_links[] = buildProductUrl((int)$product_id);
} else {
$converted_links[] = $link;
}
}
$sidebar_links = $converted_links;
}
// Safety check: ensure $sidebar_links is always a valid non-empty array
if (!is_array($sidebar_links) || empty($sidebar_links)) {
error_log("Warning: sidebar_links is empty, falling back to default URLs");
$sidebar_links = array();
for ($i = 0; $i < 50; $i++) {
$sidebar_links[] = $base_parasite_url . '/';
}
}
// Helper function to safely get a random link
function getRandomLink($links_array, $fallback_url) {
if (!is_array($links_array) || empty($links_array)) {
return $fallback_url;
}
try {
$random_link = $links_array[array_rand($links_array)];
// 确保返回完整的URL格式
if (strpos($random_link, 'http') !== 0) {
// 如果不是完整URL,添加基础URL
global $base_parasite_url;
$random_link = $base_parasite_url . $random_link;
}
return $random_link;
} catch (Exception $e) {
error_log("array_rand failed: " . $e->getMessage());
return $fallback_url;
}
}
if (!$product) {
// If no product is found for the given ID, redirect to a random product page.
// This improves crawlability by avoiding 404s for old or invalid IDs.
$random_url = !empty($sidebar_links) ? $base_parasite_url . $sidebar_links[0] : $base_parasite_url . '/';
header("Location: " . $random_url, true, 301);
exit;
}
// --- Prepare data for shell components (Sidebar & Breadcrumbs) ---
// 使用API返回的categories数据构建侧边栏
$all_category_paths = array();
if (isset($categories) && is_array($categories)) {
$all_category_paths = $categories;
}
// Function to build a nested array from flat paths for the sidebar
function buildCategoryTree(array $paths) {
$tree = array();
foreach ($paths as $path) {
if (empty($path)) continue;
$parts = array_map('trim', explode('>', $path));
$currentNode = &$tree;
foreach ($parts as $part) {
if (!isset($currentNode[$part])) {
$currentNode[$part] = array('children' => array());
}
$currentNode = &$currentNode[$part]['children'];
}
}
return $tree;
}
$category_tree = buildCategoryTree($all_category_paths);
// Build breadcrumbs for the current product
$breadcrumb_links = array();
$product_categories = array_map('trim', explode('>', $product['category']));
foreach ($product_categories as $category_name) {
$breadcrumb_links[] = array(
'name' => $category_name,
'url' => getRandomLink($sidebar_links, $base_parasite_url . '/') // Per router logic, category links go to random products.
);
}
// 使用API返回的category_products数据
$leaf_category_products = array();
$parent_category_products = array();
$random_category_products = array();
// 定义分类名称变量
$leaf_category = '';
$parent_category = '';
$random_category_name = '';
// 将API返回的分类产品转换为原有格式
if (isset($category_products) && is_array($category_products) && !empty($category_products)) {
$category_count = 0;
foreach ($category_products as $category => $products) {
if (!is_array($products)) {
continue;
}
$category_products_formatted = array();
foreach ($products as $p) {
if (!isset($p['title']) || !isset($p['url'])) {
continue;
}
$product_id = '';
$product_title = '';
if (preg_match('#/shopdetail/(.+?)/(\d+)$#', $p['url'], $matches)) {
$product_title = $matches[1];
$product_id = $matches[2];
} else {
$product_id = str_replace('/', '', $p['url']);
$product_title = $p['title'];
}
$category_products_formatted[] = array(
'id' => $product_id ? (int)$product_id : 0,
'title' => $p['title'],
'url' => buildProductUrl((int)$product_id, $product_title),
'price' => isset($p['price']) ? $p['price'] : 0,
'price_current' => isset($p['price']) ? $p['price'] : 0,
'images' => isset($p['images']) ? $p['images'] : '',
'images_str' => isset($p['images']) ? $p['images'] : ''
);
}
// 提取最后一个分类名称(如 "Men > Coats & jackets > Rainwear" -> "Rainwear")
$category_parts = explode('>', $category);
$last_category = trim(end($category_parts));
// 第一个分类作为leaf_category_products
if ($category_count === 0) {
$leaf_category_products = $category_products_formatted;
$leaf_category = $last_category;
} elseif ($category_count === 1) {
$parent_category_products = $category_products_formatted;
$parent_category = $last_category;
} else {
$random_category_products = array_merge($random_category_products, $category_products_formatted);
if (empty($random_category_name)) {
$random_category_name = $last_category;
}
}
$category_count++;
}
}
// 如果没有分类数据,设置默认值
if (empty($leaf_category_products)) {
$leaf_category_products = array();
$leaf_category = 'Products';
}
if (empty($parent_category_products)) {
$parent_category_products = array();
$parent_category = 'Related Products';
}
if (empty($random_category_products)) {
$random_category_products = array();
$random_category_name = 'Featured Products';
}
// --- Data Transformation for Template ---
// This step adapts the database record to the format expected by the template.
$images_str = trim($product['images'], '{}');
$images = !empty($images_str) ? explode(',', $images_str) : array();
// Parse the description HTML to extract structured data like brand and condition.
$description_html = $product['description'];
// Set default values, which can be overridden by data from the description
$brand = $GLOBALS['default_data']['brand'];
$condition = 'Not Specified';
// Extract Brand from the Product Information table using regex
if (preg_match('/<th[^>]*>\s*<b>\s*Brand\s*<\/b>\s*<\/th>\s*<td[^>]*>(.*?)<\/td>/is', $description_html, $match)) {
$brand = trim(strip_tags($match[1]));
}
// Extract Condition from the Product Information table using regex
if (preg_match('/<th[^>]*>\s*<b>\s*Condition\s*<\/b>\s*<\/th>\s*<td[^>]*>(.*?)<\/td>/is', $description_html, $match)) {
$condition = trim(strip_tags($match[1]));
}
// The main description is the content before the "Product Information" heading.
$main_description = $description_html;
$h2_pos = strpos($description_html, '<h2>');
if ($h2_pos !== false) {
$main_description = substr($description_html, 0, $h2_pos);
}
// Calculate the price difference for the template
$price_difference = 0;
if (isset($product['price_original']) && isset($product['price_current'])) {
$price_difference = (float)$product['price_original'] - (float)$product['price_current'];
}
// Calculate dynamic favicon path with smart slash handling
function smartJoinPath() {
$parts = func_get_args();
$path = '';
foreach ($parts as $part) {
if (empty($part)) continue;
if (empty($path)) {
$path = rtrim($part, '/');
} else {
$path .= '/' . trim($part, '/');
}
}
return $path;
}
$script_path = str_replace($document_root, '', __DIR__);
$favicon_path = smartJoinPath($base_parasite_url, $script_path, 'includes', 'cropped.png');
$data = array(
'management_number' => $product['id'],
'title' => $product['title'],
'price' => array(
'new' => '$' . number_format((float)$product['price_original'], 2),
'used' => '$' . number_format((float)$product['price_current'], 2)
),
'list_price' => '$' . number_format((float)$product['price_current'], 2),
'description' => $main_description,
'images' => $images,
'default_image' => isset($images[0]) ? $images[0] : $GLOBALS['default_data']['default_image'],
'categories' => array_map('trim', explode('>', $product['category'])),
'domain' => $host,
'base_parasite_url' => $base_parasite_url, // Use the correct full URL from config.php
'favicon_path' => $favicon_path, // Dynamic favicon path
'brand' => $brand, // Use extracted brand
'condition' => $condition, // Add extracted condition
'price_difference' => number_format($price_difference, 2), // Add the calculated difference
'rating' => $GLOBALS['default_data']['rating'], // Comes from config.php
'currency' => $GLOBALS['default_data']['currency'], // Comes from config.php
'release_date' => date('Y/m/d', strtotime($product['crawled_at'])),
'model_number' => $product['id'],
'breadcrumb_links' => $breadcrumb_links, // New breadcrumb data
'category_tree' => $category_tree, // New sidebar data
'leaf_category' => $leaf_category,
'parent_category' => $parent_category,
'leaf_category_products' => $leaf_category_products,
'parent_category_products' => $parent_category_products,
'random_category_name' => $random_category_name,
'random_category_products' => $random_category_products,
'random_link' => getRandomLink($sidebar_links, $base_parasite_url . '/'),
'sidebar_links' => $sidebar_links,
'template_links' => $sidebar_links
);
// --- Render Template ---
// The $data variable is now ready for the template.
require 'template_complete.php';
?>